// Components
import Taro from "@tarojs/taro";

// Config
import { baseUrl } from "@/config/environment";

// Hooks
import { getToken } from "./useAuth";
import useToast from "./useToast";
import { onLink } from "./useRoute";

// Utils
import qs from "qs";
import { isEmpty } from "lodash";
import { delCookie } from "./useCookie";
import { tokenKey } from "@/config/cache-keys";

function useRequest({ url, method = "post", params = {}, data = {} }) {
  const header = {};
  header.authorization = getToken();
  url = `${baseUrl}${url}`;

  if (!isEmpty(params)) {
    url = `${url}?${qs.stringify(params)}`;
  }

  return new Promise((resolve, reject) => {
    Taro.request({ url, method, header, data })
      .then((res) => {
        if (res.statusCode === 200) {
          switch (res.data.code) {
            case 200:
              resolve(res.data);
              return;

            case 401:
              onLink({
                url: `/pages/login/index`,
                linkType: "redirectTo",
              });
              delCookie(tokenKey);
              reject(res.data);
              return;
          }
        }

        const errMsg = res.data.message || res.data.msg || res.data.error || "请求失败";
        useToast(errMsg);
        reject(res.data);
      })
      .catch((error) => {
        useToast("请求失败");
        reject(error);
      });
  });
}

export default useRequest;
